package life.huangzhi.community.community.controller;

import com.sun.deploy.net.HttpResponse;
import life.huangzhi.community.community.dto.AccessTokenDTO;
import life.huangzhi.community.community.dto.GitHubUser;
import life.huangzhi.community.community.mapper.UserMapper;
import life.huangzhi.community.community.model.User;
import life.huangzhi.community.community.provider.GitHubProvider;
import life.huangzhi.community.community.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 第三方账户登录项目（gitHub）<青芸社区></>
 * @author Administrator
 * @date 2019/11/25 22:13
 */
@Controller
public class AuthorizeController {
    @Resource
    private GitHubProvider gitHubProvider;
    @Resource
    UserService userService;
    /**@Value("${key}") 会在配置文件中读取key的值*/
    @Value("${github.client.id}")
    private String clientId;
    @Value("${github.client.secret}")
    private String secret;
    @Value("${github.redirect.uri}")
    private String redirectUri;
    /**第一步：已通过前台地址执行完携带code返回
     * URl:https://github.com/login/oauth/authorize
     * ?client_id=7184bc9de0f791a3c0d2
     * &redirect_uri=http://localhost:8882/callBack&scope=user&state=1"
     *
     * @param code
     * @param state
     * */
    @GetMapping("/callback")
    public String callBack(@RequestParam(name="code") String code,
                           @RequestParam(name="state") String state,
                           HttpServletResponse response){
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setCode(code);
        accessTokenDTO.setClient_id(clientId);
        accessTokenDTO.setClient_secret(secret);
        accessTokenDTO.setRedirect_uri(redirectUri);
        accessTokenDTO.setState(state);
        //第二步通过以上参数取到授权码
        String accessToken = gitHubProvider.getAccessToken(accessTokenDTO);
        //第三步通过access_Token获取到GitHubUser(用户信息)
        GitHubUser gitHubUser = gitHubProvider.getUser(accessToken);
        if(gitHubUser!=null){
            User user = new User();
            String token = UUID.randomUUID().toString();
            user.setToken(token);
            user.setAccountId(String.valueOf(gitHubUser.getId()));
            user.setName(gitHubUser.getName());
            user.setAvatarUrl(gitHubUser.getAvatar_url());
            userService.createOrUpdate(user);
            response.addCookie(new Cookie("token",token));
            //登录成功
//            request.getSession().setAttribute("user",gitHubUser);
            return "redirect:/";
        }else {
            //登录失败
            return "redirect:/";
        }

    }
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }
}
